<template>
  <div>
      <div class="top" >
        
        <el-input  style="width: 20%;margin: 10px 10px;" placeholder="请输入分类名称" prefix-icon="el-icon-search" v-model="name" maxlength="20"></el-input>
        <el-input  style="width: 20%;margin: 10px 10px;" placeholder="请输入商品关键词" prefix-icon="el-icon-search" v-model="shopName" maxlength="20"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="searchName">搜索</el-button>
          <el-button style="float: right;" type="primary" @click="handleAdd">添加<i class="el-icon-upload el-icon--right"></i></el-button>
      </div>
      <el-table :data="product" height="700" border stripe style="width: 100%">
        <el-table-column align="center" prop="id" label="商品id" width="80"></el-table-column>
        <el-table-column align="center" prop="className" label="商品分类" width="80">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>code: {{ scope.row.code }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.className }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="商品名" width="300"></el-table-column>
        <el-table-column align="center" prop="img" label="商品图" width="300">
          <template  slot-scope="{ row }">
            <img  style="width:300px;height: 200px" :src="row.img"  alt=""  />
          </template>
        </el-table-column> 
        <el-table-column align="center" prop="price" label="单价" width="80"></el-table-column>   
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit"  @click="handleUpdata(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete"  @click="handleDel(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="addVisible" :modal-append-to-body="false" width="60%" top="0" title="新增" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="商品分类" prop="className">
              <el-select v-model="ruleForm.className" placeholder="请选择">
                <el-option
                  v-for="(item,index) in classNameList"
                  :key="index"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input  v-model="ruleForm.name" ></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input type="number" v-model="ruleForm.price" ></el-input>
            </el-form-item>
            <el-form-item label="原价" prop="oldPrice">
              <el-input type="number" v-model="ruleForm.oldPrice" ></el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="img">
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img style="width: 200px" v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item  label="商品详情" prop="introduce">
							<editor-bar :catchData="catchData"  v-model="ruleForm.introduce" :content="editorContent" ></editor-bar>  
						</el-form-item>
            <el-form-item label="商品图片组" prop="urlList">
              <el-upload
                action="http://127.0.0.1:3000/v1/upload/upload"
                list-type="picture-card"
                :on-success="handleSuccess"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" add('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog :visible.sync="updataVisible" :modal-append-to-body="false" width="60%" top="0" title="修改" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="商品分类" prop="className">
              <el-select v-model="ruleForm.className" placeholder="请选择">
                <el-option
                  v-for="(item,index) in classNameList"
                  :key="index"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item  readonly="readonly" label="商品名称" prop="name">
              <el-input  v-model="ruleForm.name" ></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input type="number" v-model="ruleForm.price" ></el-input>
            </el-form-item>
            <el-form-item label="原价" prop="oldPrice">
              <el-input type="number" v-model="ruleForm.oldPrice" ></el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="img">
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img style="width: 200px" v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品图片组" prop="urlList">
              <el-upload
                action="http://127.0.0.1:3000/v1/upload/upload"
                list-type="picture-card"
                :on-success="handleSuccess"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <el-form-item  label="商品详情" prop="introduce">
							<editor-bar :catchData="catchData"  v-model="ruleForm.introduce" :content="editorContent" ></editor-bar>  
						</el-form-item>
            
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updataReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" updata('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
  </div>

</template>

<script>
 import EditorBar from "@/components/editoritem.vue"
import myaxios from '../http/MyAxios'
import { BASE_URL } from '@/config'
  export default {
    components: { EditorBar} ,
    data() {
            
      var Pass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPassword !== '') {
            this.$refs.ruleForm.validateField('checkPassword');
          }
          callback();
        }
      };
      var Pass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        url:'',
        urlList:'',
        dialogImageUrl: '',
        dialogVisible: false,
        product:[],
        productClass:[],
        classNameList:[],
        id:0,
        name:'',
        shopName:'',
        imageUrl: '',
        addVisible: false,
        updataVisible:false,
        loading: false,
        form:[],
        ruleForm: {
          introduce:'',
          className:'',
          code:'',
          name: '',
          img: '',
          price:'',
          oldPrice:''
         
        },
        rules:{
          className:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          code:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          name:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          price:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          oldPrice:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          // img:[
          // {required:true,message:'该字段必填',trigger:'blur'},
          // ],
        }
      }
    },
    beforeMount(){
      this.getProduct()
      this.getProductClass()

    },
    methods: {
      handleSuccess(response){
        this.url = response.result
        this.urlList =  this.url +"," +this.urlList
      },
      handleRemove(file, fileList) {

      },

       // 监听富文本的输入
       catchData(e) {
        this.ruleForm.introduce =e
      
      },
      //富文本中的内容
      editorContent(e) {
        
      },

      handleAvatarSuccess(res) {
        this.imageUrl = res.result;
      },
      updataReset(formName) {
        this.$refs[formName].resetFields();
        this.ruleForm = {}
        this.imageUrl = ''
      },
      updata(formName){
        let url1= BASE_URL + '/v1/index/classNameSearch'
        myaxios.get(url1,{name:this.ruleForm.className}).then(res=>{
             this.ruleForm.code = res.data.data[0].code
             this.$refs[formName].validate((valid) => {
                if (valid) {
                this.form.id = this.id
                this.form.className =  this.ruleForm.className
                this.form.code = this.ruleForm.code
                this.form.name =  this.ruleForm.name
                this.form.price =  this.ruleForm.price
                this.form.oldPrice =  this.ruleForm.oldPrice
                this.form.img =  this.imageUrl
                this.form.urlList = this.urlList
                this.form.introduce = this.ruleForm.introduce
                  let url=BASE_URL + '/v1/product/productUpdate'
                    myaxios.post(url,this.form).then(()=>{
                      this.$message({
                        showClose: true,
                        message: '恭喜你，修改成功',
                        type: 'success'
                      });

                      this.getProduct()
                      this.updataVisible = false
                      }).catch(err=>{
                          console.warn(err);
                        })
                } else {
                  alert('提交失败');
                  return false;
                }
              });
        })
        
      },
      handleUpdata(row){
        this.id = row.id
        this.imageUrl = row.img
        let url=BASE_URL + '/v1/product/idSearch'
        let params = {id:this.id}
        myaxios.get(url,params).then(res=>{
          this.ruleForm = res.data.data[0]
          this.updataVisible = true
        }).catch(err=>{
          console.warn(err);
        })
      },
      addReset(formName) {
        this.$refs[formName].resetFields();
      },
      add(formName) {
        
        let url1= BASE_URL + '/v1/index/classNameSearch'
        myaxios.get(url1,{name:this.ruleForm.className}).then(res=>{
             this.ruleForm.code = res.data.data[0].code
            
             this.$refs[formName].validate((valid) => {
                if (valid) {
                  this.form.className =  this.ruleForm.className
                  this.form.code = this.ruleForm.code
                  this.form.name =  this.ruleForm.name
                  this.form.price =  this.ruleForm.price
                  this.form.oldPrice =  this.ruleForm.oldPrice
                  this.form.img =  this.imageUrl
                  this.form.introduce = this.ruleForm.introduce
                  this.form.urlList =this.urlList               
                    let url=BASE_URL + '/v1/product/productAdd'
                    console.log(this.form);
                      myaxios.post(url,this.form).then(()=>{
                        this.$message({
                          showClose: true,
                          message: '恭喜你，提交成功',
                          type: 'success'
                        });
                        this.getProduct()
                        this.addVisible = false
                        }).catch(err=>{
                            console.warn(err);
                          })
                  } else {
                    alert('提交失败');
                    return false;
                  }
                });
          }).catch(err=>{
          console.warn(err);
          })
        
      },
      handleAdd(){
      this.imageUrl = ''
      this.urlList = ''
      this.ruleForm.introduce = ''
      this.ruleForm = {}
       this.addVisible = true
    
      },
      handleDel(row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url=BASE_URL + '/v1/product/productDelete'
          let params = {id:row.id}
            myaxios.get(url,params).then(()=>{
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getProduct()
              }).catch(err=>{
                    console.warn(err);
                 })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      Close(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      searchName(){
        let url=BASE_URL + '/v1/product/FuzzySearch'
        myaxios.get(url,{
          className: this.name,
          name: this.shopName
        }).then(res=>{
          if (res.data.code == 200){
            this.product = res.data.data
          }else{
            this.$message({
                  showClose: true,
                  message: '查询失败,未找到相关商品',
                 type: 'warning'
                });
          }
        }).catch(()=>{
          this.$message({
                  showClose: true,
                  message: '查询失败,未找到相关商品',
                  type: 'error'
                });
        })
      },
      getProductClass(){
        let url=BASE_URL + '/v1/index/productClassSearch'
        myaxios.get(url).then(res=>{
          this.productClass = res.data.data
          for(var i=0;i<=this.productClass.length;i++){
            this.classNameList.push(this.productClass[i].name) 
          }
        }).catch(err=>{
          console.warn(err);
        })
    },
      getProduct(){
        let url=BASE_URL + '/v1/product/allSearch'
        myaxios.get(url).then(res=>{
          this.product = res.data.data
        }).catch(err=>{
          console.warn(err);
        })
    },
    },
  }
</script>
<style scoped lang="scss">

</style>